package rabbitmq.routing;

import com.rabbitmq.client.*;

import java.io.IOException;

/**
 * @Author ：腾杰
 * @Date ：2021年09月17日 0017 21:52
 * @Description ：广播模式
 */
public class Consumer {

    private static Runnable runnable = () -> {

        // 1: 创建连接工厂
        ConnectionFactory connectionFactory = new ConnectionFactory();

        // 2: 设置连接属性
        connectionFactory.setHost("8.130.160.38");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("/");
        connectionFactory.setUsername("admin");
        connectionFactory.setPassword("admin");
        //获取队列的名称
        final String queueName = Thread.currentThread().getName();
        Connection connection = null;
        Channel channel = null;

        // 3: 从连接工厂中获取连接
        try {

            connection = connectionFactory.newConnection("生产者");
            // 4: 从连接中获取通道channel
            channel = connection.createChannel();

            channel.basicConsume(queueName, true, new DeliverCallback() {
                public void handle(String s, Delivery delivery) throws IOException {
                    System.out.println("收到消息" + new String(delivery.getBody(), "UTF-8"));
                }
            }, new CancelCallback() {
                public void handle(String s) throws IOException {
                    System.out.println("失败");
                }
            });

            System.in.read();
        } catch (Exception e) {

            e.printStackTrace();

        } finally {

            if (channel != null && channel.isOpen()) {
                try {
                    channel.close();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }

            if (connection != null) {

                try {
                    connection.close();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }

            }

        }


        // 4: 从连接中获取通道channel


    };

    public static void main(String[] args) {
        // 启动三个线程去执行
        new Thread(runnable, "queue-1").start();
        new Thread(runnable, "queue-2").start();
        new Thread(runnable, "queue-3").start();
    }
}
